package admin

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
)

type NewjournalLog struct {
	ID           int    `json:"id"`
	Type         int    `json:"type"`          //类型 2新增 3编辑 4删除 5排序
	OperatorUid  int    `json:"operator_uid"`  //操做人
	CreatedStart string `json:"created_start"` //开始时间
	CreatedEnd   string `json:"created_end"`   //结束时间
	Page         int    `json:"page"`
	Limit        int    `json:"limit"`
}
type JournalLogSucc struct {
	ID           int    `gorm:"type:int(10); primaryKey" json:"id"`
	Type         int    `gorm:"type:int(10);" json:"type"`         //类型 2新增 3编辑 4删除 5排序 6状态
	Remarks      string `gorm:"type:varchar(255);" json:"remarks"` //备注
	OperatorUid  int    `gorm:"type:int(10);" json:"operator_uid"` //操做人id
	OperatorName string `gorm:"type:varchar(255);"json:"operator_name"`
	Content      string `gorm:"type:varchar(255);" json:"content"` //日志内容
	CreatedAt    int    `gorm:"type:int(10);" json:"created_at"`
	UpdatedAt    int    `gorm:"type:int(10);" json:"updated_at"`
}

// 操作日志
func JournalLogList(c *gin.Context) {
	//接收
	var jsonData NewjournalLog
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var list []JournalLogSucc
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	selectData := "m_journalL_log.id,m_journalL_log.type,m_journalL_log.remarks,m_journalL_log.operator_uid,m_journalL_log.content,m_journalL_log.created_at,m_admin_user.user_name as operator_name"
	tx := models.DB.Table("m_journalL_log").Select(selectData).Joins("left join m_admin_user on m_admin_user.id=m_journalL_log.operator_uid")
	if jsonData.ID > 0 {
		tx = tx.Where("m_journalL_log.id=?", jsonData.ID)
	}
	if jsonData.Type > 0 {
		tx = tx.Where("m_journalL_log.type=?", jsonData.Type)
	}
	if jsonData.OperatorUid > 0 {
		tx = tx.Where("m_journalL_log.operator_uid=?", jsonData.OperatorUid)
	}
	if jsonData.CreatedStart != "" {
		tx = tx.Where("m_journalL_log.created_at>?", define.TimeUnix(jsonData.CreatedStart))
	}
	if jsonData.CreatedEnd != "" {
		tx = tx.Where("m_journalL_log.created_at<?", define.TimeUnix(jsonData.CreatedEnd))
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if tx.Error != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  tx.Error,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}
